﻿namespace MicroCloud.Identity.Database
{
    /// <summary>
    /// 组织机构种子数据初始值设定项
    /// </summary>
    [Description("系统组织机构种子数据")]
    public class OrganizationSeedDataInitializer : SeedDataInitializerBase<Organization, long>
    {
        /// <summary>
        /// 初始化一个组织机构种子数据初始值设定项 <see cref="OrganizationSeedDataInitializer"/> 的新实例
        /// </summary>
        /// <param name="rootProvider"></param>
        public OrganizationSeedDataInitializer(IServiceProvider rootProvider)
            : base(rootProvider)
        { }

        /// <summary>
        /// 重写以提供要初始化的种子数据
        /// </summary>
        /// <param name="provider">服务提供者</param>
        /// <returns></returns>
        protected override Organization[] SeedData(IServiceProvider provider)
        {
            var name = "MicroCloud";
            return new[]
            {
                new Organization()
                {
                    Code = "001",
                    Type =  OrganizationType.Virtual,
                    Name = name,
                    NormalizedName = name.ToUpper(),
                    Description = "系统默认组织，可以根据实际业务需要定制。",
                    OrderNo = 1,
                    EnableLogin = true,
                    IsDefault = true,
                    IsSystem = true,
                    Portfolio = new OrganizationPortfolio() { Avatar = StaticHelper.GetImgBase64String(ImageName.OrgLogo) },
                    Detail = new OrganizationDetail() { ReptName = name, PrintHeader = name },
                }
            };
        }

        /// <summary>
        /// 重写以提供判断某个实体是否存在的表达式
        /// </summary>
        /// <param name="entity">要判断的实体</param>
        /// <returns></returns>
        protected override Expression<Func<Organization, bool>> ExistingExpression(Organization entity)
        {
            return m => m.Code.Equals(entity.Code) || m.Name.Equals(entity.Name);
        }

        /// <summary>
        /// 将种子数据初始化到数据库
        /// </summary>
        /// <param name="entities">实体对象数组</param>
        /// <param name="provider">服务提供者</param>
        protected override void SyncToDatabase(Organization[] entities, IServiceProvider provider)
        {
            if (entities == null || entities.Length == 0)
            {
                return;
            }

            provider.BeginUnitOfWorkTransaction(provider =>
            {
                IRepository<Organization, long> repository = provider.GetService<IRepository<Organization, long>>();
                //IRepository<OrganizationDetail, long> detailRepository = provider.GetService<IRepository<OrganizationDetail, long>>();
                //IRepository<OrganizationPortfolio, long> portfolioRepository = provider.GetService<IRepository<OrganizationPortfolio, long>>();
                foreach (var entity in entities)
                {
                    if (repository.CheckExists(ExistingExpression(entity)))
                    {
                        continue;
                    }

                    //父模块检查
                    string parentTreePathString = null;
                    if (entity.ParentId != null && entity.ParentId > 0)
                    {
                        var parent = repository.QueryAsNoTracking().Where(m => m.Id.Equals(entity.ParentId)).Select(m => new { m.Id, m.TreePathString }).FirstOrDefault() ?? throw new Exception(I18N.T("组织机构 {0} 不存在", entity.ParentId));
                        entity.ParentId = entity.ParentId;
                        parentTreePathString = parent.TreePathString;
                    }
                    else
                    {
                        entity.ParentId = null;
                    }
                    //持久化实体数据
                    var result = repository.Insert(entity);
                    if (result.Succeeded)
                    {
                        entity.TreePathString = entity.ParentId == null ? TreeHelper.FormatTreePathString(entity.Id) : TreeHelper.GetTreePathString(entity.Id, parentTreePathString);
                        repository.Update(entity);
                    }

                }
            });
        }

    }

}
